package com.huabo.contract.controller;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huabo.contract.manager.FileManager;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.ImportOrExportExcelUtil;
import com.hbfk.util.JudgeRoleRight;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.huabo.contract.oracle.entity.TblCyhwProjectbudget;
import com.huabo.contract.oracle.entity.TblCyhwUnit;
import com.huabo.contract.service.TblCyhwUnitService;
import com.huabo.contract.service.TblOrganizaService;
import com.huabo.contract.util.DateUtils;
import com.huabo.contract.util.ExcelUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@Api(value = "合同台账Controller", tags = {"合同台账所有接口"})
public class ContractAccountController {

    @Resource
    private TblCyhwUnitService tblCyhwUnitService;

    @Resource
    public TblOrganizaService tblOrganizaService;

    /**
     * 合同台账列表
     */
    @RequestMapping(value = "/contract/contractLedgerList", method = {RequestMethod.POST}, produces = "application/html; charset=utf-8")
    @ApiOperation(value = "合同台账列表")
    public String contract_contractLedgerList(HttpServletRequest request,
                                              @ApiParam(value = "startdate", required = false) String startdate,
                                              @ApiParam(value = "enddate", required = false) String enddate,
                                              @ApiParam(name = "pageNumber", value = "当前页", required = false, defaultValue = "1") Integer pageNumber,
                                              @ApiParam(name = "pageSize", value = "每页数量", required = false, defaultValue = "10") Integer pageSize,
											  @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
                                              @ApiParam(name = "staffId", value = "用户Id主键", required = false) String staffId,
                                              TblCyhwUnit unit) {
        String result = null;
        try {
            Map<String, Object> resultMap = this.tblCyhwUnitService.findLedgerListPageInfo(token, staffId, startdate, enddate, pageNumber, pageSize, unit);
            JSONObject jsonObj = new JSONObject(resultMap);
            result = jsonObj.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 合同台账导出
     *
     * @param request
     * @return
     */
	@RequestMapping(value = "/contract/exploredInfo",method = {RequestMethod.POST}, produces = "application/html; charset=utf-8")
	@ResponseBody
	public void  contract_contractLedgerList(HttpServletRequest request, HttpServletResponse response,
											 TblCyhwUnit unit,
											 @RequestParam(value="startdate1",required=false)String startdate1,
											 @RequestParam(value="enddate1",required=false)String enddate1,
											 @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
											 @ApiParam(name="staffId",value="用户Id主键",required=false)String staffId) {
		try {
			log.info("合同管理--相对方管理--黑名单管理---导出Excel");
			response.setContentType("application/binary;charset=UTF-8");
			TblStaffUtil staff = DealUserToken.parseUserToken(token);
			unit.setOrgid(staff.getCurrentOrg().getOrgid());
			Integer resultCount = this.tblOrganizaService.findCountByUserSjb(staff.getStaffid());
			if(!JudgeRoleRight.judgeRoleRight("合同管理员",staff.getRoleNames())){
				unit.setCreateuser(staff.getStaffid());
			}
			Date enddate = null;
			if(enddate1 == null) {
				enddate = new Date();
			}else {
				enddate = DateUtils.parse(enddate1, "yyyy-MM-dd");
			}
			Date startdate = null;
			if(startdate1 == null) {
				Calendar cal = Calendar.getInstance();
				startdate = DateUtils.parse(cal.get(Calendar.YEAR)+"-01-01","yyyy-MM-dd");
			}else {
				startdate = DateUtils.parse(startdate1,"yyyy-MM-dd");
			}
			unit.setEnddate(enddate);
			unit.setStartdate(startdate);
			List<TblCyhwUnit> unitList = this.tblCyhwUnitService.findLedgerListForExport(unit);
			String[] cNames = { "合同编号", "合同名称","相对方名称","合同类型", "项目名称","收付款方向", "合同金额", "创建日期", "开始日期","结束日期","我方签署主体","承办部门","执行人","附件数","用印日期","状态"};
			List<Object[]> contractlist = new ArrayList<Object[]>(0);
			Object[] objs = null;
			
			for (TblCyhwUnit ui : unitList) {
				objs = new Object[16];
				objs[0] = ui.getContractno();
				objs[1] = ui.getContractname();
				objs[2] = ui.getRecordConcatname();
				objs[3] = ui.getContracttype();
				objs[4] = ui.getTopicname();
				objs[5] = ui.getDctype();
				objs[6] = ui.getContractmoney();
				objs[7] = ui.getCreatetime()==null?"":DateUtils.parseDate(ui.getCreatetime(), "yyyy-MM-dd");
				objs[8] = ui.getStartdate()==null?"":DateUtils.parseDate(ui.getStartdate(), "yyyy-MM-dd");
				objs[9] = ui.getEnddate()==null?"":DateUtils.parseDate(ui.getEnddate(), "yyyy-MM-dd");
				objs[10] = ui.getChoicejbunitid();
				objs[11] = ui.getChoicecontractDeptId();
				objs[12] = ui.getTopic();
				objs[13] = ui.getNodeCount();
				objs[14] = ui.getYongyintime()==null?"":DateUtils.parseDate(ui.getYongyintime(), "yyyy-MM-dd");
				objs[15] = this.getContractStatusText(ui.getContractstatus());
				contractlist.add(objs);
			}
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("合同台账".getBytes(),"UTF-8") + ".xlsx");
			ServletOutputStream outputStream = response.getOutputStream();
			ImportOrExportExcelUtil.exportExcel(cNames, contractlist, outputStream, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


    public String getContractStatusText(Integer cstatus) {
        String result = null;

        switch (cstatus) {
            case 1:
                result = "审批中";
                break;
            case 2:
                result = "需调整";
                break;
            case 3:
                result = "已通过";
                break;
            case 4:
                result = "已终止";
                break;
            case 5:
                result = "已跟踪";
                break;
            case 6:
                result = "已完成";
                break;
            case 7:
                result = "执行中";
                break;
            case 8:
                result = "已归档";
                break;
            case 9:
                result = "已暂停";
                break;
            case 10:
                result = "已变更";
                break;
            case 11:
                result = "已终止";
                break;
            default:
                result = "未审批";
                break;
        }
        return result;
    }


//    @RequestMapping(value = "/contract/exploredInfo",method = {RequestMethod.POST}, produces = "application/html; charset=utf-8")
//    @ResponseBody
//    public void  contract_contractLedgerList(HttpServletRequest request, HttpServletResponse response,
//                                             TblCyhwUnit unit,
//                                             @RequestParam(value="startdate1",required=false)String startdate1,
//                                             @RequestParam(value="enddate1",required=false)String enddate1,
//                                             @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
//                                             @ApiParam(name="staffId",value="用户Id主键",required=false)String staffId) {
//        try {
//            TblStaffUtil staff = DealUserToken.parseUserToken(token);
//            unit.setOrgid(staff.getCurrentOrg().getOrgid());
//            Integer resultCount = this.tblOrganizaService.findCountByUserSjb(staff.getStaffid());
//            if(resultCount == 0 && staff.getTrole()!=null && !"合同管理员".equals(staff.getTrole().getRname())){
//                unit.setCreateuser(staff.getStaffid());
//            }
//            Date enddate = null;
//            if(enddate1 == null) {
//                enddate = new Date();
//            }else {
//                enddate = DateUtils.parse(enddate1, "yyyy-MM-dd");
//            }
//            Date startdate = null;
//            if(startdate1 == null) {
//                Calendar cal = Calendar.getInstance();
//                startdate = DateUtils.parse(cal.get(Calendar.YEAR)+"-01-01","yyyy-MM-dd");
//            }else {
//                startdate = DateUtils.parse(startdate1,"yyyy-MM-dd");
//            }
//            unit.setEnddate(enddate);
//            unit.setStartdate(startdate);
//            List<TblCyhwUnit> unitList = this.tblCyhwUnitService.findLedgerListForExport(unit);
//            String[] cNames = { "合同编号", "合同名称","相对方名称","合同类型", "合同项目","收付款方向", "合同金额", "合同类型", "创建日期", "开始日期","结束日期","执行单位","执行部门","执行人","附件数","用印份数","用印日期","状态"};
//            SXSSFWorkbook wb = new SXSSFWorkbook();//创建空excel文件
//            Sheet sheet = wb.createSheet();
//            Row row = sheet.createRow(0);
//            for(int i=1; i<=18; i++){
//                row.createCell(i);
//            }
//            sheet.addMergedRegion(new CellRangeAddress(0,0,1,18));
//            row.getCell(1).setCellValue("合同台账");
//            row = sheet.createRow(1); //创建第二行标题行
//            row.createCell(1).setCellValue("合同编号");
//            row.createCell(2).setCellValue("合同名称");
//            row.createCell(3).setCellValue("相对方名称");
//            row.createCell(4).setCellValue("合同类型");
//            row.createCell(5).setCellValue("合同项目");
//            row.createCell(6).setCellValue("收付款方向");
//            row.createCell(7).setCellValue("合同金额");
//            row.createCell(8).setCellValue("合同类型");
//            row.createCell(9).setCellValue("创建日期");
//            row.createCell(10).setCellValue("开始日期");
//            row.createCell(11).setCellValue("结束日期");
//            row.createCell(12).setCellValue("执行单位");
//            row.createCell(13).setCellValue("执行部门");
//            row.createCell(14).setCellValue("执行人");
//            row.createCell(15).setCellValue("附件数");
//            row.createCell(16).setCellValue("用印份数");
//            row.createCell(17).setCellValue("用印日期");
//            row.createCell(18).setCellValue("状态");
//
//            ExcelUtil exportUtil = new ExcelUtil("合同台账", cNames);
//            HSSFCell cell = null;
//            HSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
//            bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//            if (unitList != null && unitList.size() > 0) {
//                TblCyhwUnit ui = null;
//                for (int i = 0; i < unitList.size(); i++) {
//                    HSSFRow bodyRow = exportUtil.getNextRow(i + 1);// 创建表格行
//                    ui = unitList.get(i);
//
//                    cell = bodyRow.createCell(0);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContractno());
//                    cell = bodyRow.createCell(1);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContractname());
//                    cell = bodyRow.createCell(2);
//                    cell.setCellStyle(bodyStyle);
//                    if(ui.getRecordConcatname() != null ) {
//                        cell.setCellValue(ui.getRecordConcatname());
//                    }else {
//                        cell.setCellValue("");
//                    }
//                    cell = bodyRow.createCell(3);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContracttype());
//                    cell = bodyRow.createCell(4);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContractitem());
//
//                    cell = bodyRow.createCell(5);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getDctype());
//                    cell = bodyRow.createCell(6);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContractmoney().toString());
//                    cell = bodyRow.createCell(7);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getContracttype());
//
//                    cell = bodyRow.createCell(8);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(DateUtils.parseDate(ui.getCreatetime(), "yyyy-MM-dd"));
//                    cell = bodyRow.createCell(9);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(DateUtils.parseDate(ui.getStartdate(), "yyyy-MM-dd"));
//                    cell = bodyRow.createCell(10);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(DateUtils.parseDate(ui.getEnddate(), "yyyy-MM-dd"));
//                    //"执行单位","执行部门","执行人","附件数","用印份数","用印日期"
//
//                    cell = bodyRow.createCell(11);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getChoicejbunitid());
//                    cell = bodyRow.createCell(12);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getChoicecontractDeptId());
//                    cell = bodyRow.createCell(13);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(ui.getTopic());
//                    cell = bodyRow.createCell(14);
//                    cell.setCellStyle(bodyStyle);
//                    if(ui.getNodeCount() == null){
//                        ui.setNodeCount(0);
//                    }
//                    cell.setCellValue(ui.getNodeCount());
//                    cell = bodyRow.createCell(15);
//                    cell.setCellStyle(bodyStyle);
//                    if(ui.getYongyinnum() == null){
//                        ui.setYongyinnum(0);
//                    }
//                    cell.setCellValue(ui.getYongyinnum());
//                    cell = bodyRow.createCell(16);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(DateUtils.parseDate(ui.getYongyintime(), "yyyy-MM-dd"));
//                    cell = bodyRow.createCell(17);
//                    cell.setCellStyle(bodyStyle);
//                    cell.setCellValue(this.getContractStatusText(ui.getContractstatus()));
//                }
//            }
//            exportUtil.writeOut(response, "合同台账.xls");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
	@Resource
	private FileManager fileManager;

	@ApiOperation(value="上传图片接口")
	@RequestMapping(value = "/upload",method = {RequestMethod.POST} , produces = "application/html; charset=utf-8")
	public String upload(MultipartFile file,
						 @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token ) {
		String result = null;
		try {
			Map<String,Object>  resultMap = fileManager.upload(file,token);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


}
